<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item
        label="环境光谱编号"
        prop="envSpectrumNo"
        label-width="100px"
      >
        <el-input
          v-model="queryParams.envSpectrumNo"
          placeholder="请输入环境光谱编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="部门名称" prop="departmentName">
        <el-select
          v-model="queryParams.departmentName"
          size="small"
          placeholder="请选择部门"
          clearable
        >
          <el-option
            v-for="item in options.departments"
            :key="item.deptId"
            :label="item.deptName"
            :value="item.deptName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="仪器编号" prop="instrumentNo">
        <el-input
          v-model="queryParams.instrumentNo"
          placeholder="请输入仪器编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仪器名称" prop="instrumentName">
        <el-input
          v-model="queryParams.instrumentName"
          placeholder="请输入仪器名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="采样人" prop="builderName">
        <el-input
          v-model="queryParams.builderName"
          placeholder="请输入采样人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="采样时间" prop="samplingTime">
        <el-date-picker
          clearable
          v-model="queryParams.samplingTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择采样时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row v-if="isRowVisible" :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['spectrum:env_spectrum:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['spectrum:env_spectrum:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['spectrum:env_spectrum:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['spectrum:env_spectrum:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 弹窗 -->
    <el-dialog
      title="上传光谱数据文件"
      :visible.sync="showModal"
      width="50%"
      :before-close="handleClose"
    >
      <el-upload
        class="upload-demo"
        drag
        action=""
        :auto-upload="false"
        :on-change="handleFileUpload"
        :show-file-list="false"
        accept=".txt"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传txt文件</div>
      </el-upload>

      <div v-if="fileContent" class="file-info">
        <el-divider content-position="left">文件解析结果</el-divider>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="光谱仪型号">{{
            spectrometerModel
          }}</el-descriptions-item>
          <el-descriptions-item label="波长范围">{{
            wavelengthRange
          }}</el-descriptions-item>
          <el-descriptions-item label="吸光度数据">
            <el-tooltip
              effect="dark"
              :content="absorbanceString"
              placement="top"
            >
              <span>{{ absorbanceDataPreview }}...</span>
            </el-tooltip>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <div class="drawer-footer">
        <el-button @click="resetForm">取 消</el-button>
        <el-button type="primary" @click="saveData" :disabled="!fileContent"
          >保 存</el-button
        >
      </div>
    </el-dialog>

    <el-table
      ref="envTable"
      v-loading="loading"
      :data="env_spectrumList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="环境光谱编号"
        align="center"
        prop="envSpectrumNo"
      />
      <!-- <el-table-column label="波长" align="center" prop="wavelength" show-overflow-tooltip/> -->
      <el-table-column label="部门名称" align="center" prop="departmentName" />
      <el-table-column label="仪器编号" align="center" prop="instrumentNo" />
      <el-table-column label="仪器名称" align="center" prop="instrumentName" />
      <!-- <el-table-column label="起始波长" align="center" prop="startWavelength" />
      <el-table-column label="结束波长" align="center" prop="endWavelength" /> -->
      <el-table-column
        label="采样时间"
        align="center"
        prop="samplingTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.samplingTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="采样人" align="center" prop="builderName" />
      <el-table-column label="备注" align="center" prop="remarks" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        v-if="isRowVisible"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['spectrum:env_spectrum:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['spectrum:env_spectrum:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改环境光谱对话框 -->
    <el-drawer :title="title" :visible.sync="open" size="400px" append-to-body>
      <div
        style="padding-left: 20px; padding-right: 20px; padding-bottom: 20px"
      >
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="medium"
          style="width: 100%"
          @click="showModal = true"
        >
          导入光谱
        </el-button>
      </div>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="120px"
        style="padding-right: 20px"
      >
        <!-- <el-form-item label="环境光谱编号" prop="envSpectrumNo">
          <el-input
            v-model="form.envSpectrumNo"
            placeholder="请输入环境光谱编号"
          />
        </el-form-item> -->
        <el-form-item label="波长" prop="wavelength">
          <el-input
            v-model="form.wavelength"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="部门名称" prop="departmentName">
          <el-select
            v-model="form.departmentName"
            size="small"
            placeholder="请选择部门"
            clearable
            @change="handleDepartmentChange"
          >
            <el-option
              v-for="item in options.departments"
              :key="item.deptId"
              :label="item.deptName"
              :value="item.deptName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="仪器编号" prop="instrumentNo">
          <el-input v-model="form.instrumentNo" placeholder="请输入仪器编号" />
        </el-form-item>
        <el-form-item label="仪器名称" prop="instrumentName">
          <el-input
            v-model="form.instrumentName"
            placeholder="请输入仪器名称"
          />
        </el-form-item>
        <el-form-item label="起始波长" prop="startWavelength">
          <el-input
            v-model="form.startWavelength"
            placeholder="请输入起始波长"
          />
        </el-form-item>
        <el-form-item label="结束波长" prop="endWavelength">
          <el-input v-model="form.endWavelength" placeholder="请输入结束波长" />
        </el-form-item>
        <el-form-item label="采样时间" prop="samplingTime">
          <el-date-picker
            clearable
            v-model="form.samplingTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择采样时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="采样人" prop="builderName">
          <el-input v-model="form.builderName" placeholder="请输入采样人" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input
            v-model="form.remarks"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <div class="drawer-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import {
  listEnv_spectrum,
  getEnv_spectrum,
  delEnv_spectrum,
  addEnv_spectrum,
  updateEnv_spectrum,
} from "@/api/spectrum/env_spectrum";
import { listData as listInstrument } from "@/api/instrument/data";
import { listDept } from "@/api/system/dept";

export default {
  name: "Env_spectrum",
  props: {
    isRowVisible: {
      type: Boolean,
      default: true,
    },
  },

  data() {
    return {
      options: {},
      showModal: false,
      fileContent: null,
      spectrometerModel: "",
      wavelengthRange: "",
      samplingTime: "",
      absorbanceData: [],
      absorbanceString: "",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 环境光谱表格数据
      env_spectrumList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        envSpectrumNo: null,
        wavelength: null,
        departmentName: null,
        departmentId: null,
        instrumentId: null,
        instrumentNo: null,
        instrumentName: null,
        startWavelength: null,
        endWavelength: null,
        samplingTime: null,
        builderId: null,
        builderName: null,
        remarks: null,
        isDelete: null,
        creatorId: null,
        creator: null,
        modifierId: null,
        modifier: null,
        modifyTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        envSpectrumNo: [
          { required: true, message: "环境光谱编号不能为空", trigger: "blur" },
        ],
        wavelength: [
          { required: true, message: "波长不能为空", trigger: "blur" },
        ],
        departmentName: [
          { required: true, message: "部门名称不能为空", trigger: "blur" },
        ],
        departmentId: [
          { required: true, message: "部门id不能为空", trigger: "blur" },
        ],
        instrumentId: [
          { required: true, message: "仪器id不能为空", trigger: "blur" },
        ],
        instrumentNo: [
          { required: true, message: "仪器编号不能为空", trigger: "blur" },
        ],
        instrumentName: [
          { required: true, message: "仪器名称不能为空", trigger: "blur" },
        ],
        startWavelength: [
          { required: true, message: "起始波长不能为空", trigger: "blur" },
        ],
        endWavelength: [
          { required: true, message: "结束波长不能为空", trigger: "blur" },
        ],
        samplingTime: [
          { required: true, message: "采样时间不能为空", trigger: "blur" },
        ],
        builderId: [
          { required: true, message: "采样人id不能为空", trigger: "blur" },
        ],
        builderName: [
          { required: true, message: "采样人不能为空", trigger: "blur" },
        ],
        isDelete: [
          { required: true, message: "是否删除不能为空", trigger: "blur" },
        ],
        creatorId: [
          { required: true, message: "新增人id不能为空", trigger: "blur" },
        ],
        creator: [
          { required: true, message: "新增人不能为空", trigger: "blur" },
        ],
        createTime: [
          { required: true, message: "新增时间不能为空", trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    absorbanceDataPreview() {
      return this.absorbanceString.substring(0, 50);
    },
  },
  created() {
    this.getList();
    this.getDepartments();
  },
  methods: {
    handleDepartmentChange(deptName) {
      const dept = this.options.departments.find(
        (dept) => dept.deptName === deptName
      );
      if (dept) {
        this.form.departmentId = dept.deptId;
      } else {
        this.$modal.msgError("部门不存在");
        this.form.departmentId = null;
      }
    },
    /** 获取部门列表 */
    async getDepartments() {
      try {
        const response = await listDept(); // 替换为实际的部门列表API
        this.options.departments = response.data;
        console.log("获取部门列表成功:", response.data);
      } catch (error) {
        console.error("获取部门列表失败:", error);
      }
    },
    handleClose(done) {
      this.resetForm();
      done();
    },
    handleFileUpload(file) {
      const reader = new FileReader();
      reader.onload = async (e) => {
        const arrayBuffer = e.target.result;
        this.detectAndParseFile(arrayBuffer);
      };
      reader.readAsArrayBuffer(file.raw); // 改成读取二进制
    },
    async detectAndParseFile(buffer) {
      const encodings = ["utf-8", "gbk", "gb2312"];
      let decoded = null;

      for (const encoding of encodings) {
        try {
          const decoder = new TextDecoder(encoding);
          const content = decoder.decode(buffer);
          if (!content.includes("��")) {
            // 没乱码就说明成功
            decoded = content;
            console.log("使用编码: ", encoding);
            break;
          }
        } catch (e) {
          console.error(`尝试${encoding}失败`, e);
        }
      }

      if (!decoded) {
        this.$message.error("文件编码不支持，请使用UTF-8或GBK编码的文件");
        return;
      }

      this.fileContent = decoded;
      this.parseFileContent();
    },
    parseFileContent() {
      if (!this.fileContent) return;
      const lines = this.fileContent.split("\n");
      console.log("lines", lines);
      // 解析光谱仪信息
      lines.forEach((line) => {
        if (line.includes("光谱仪型号:")) {
          this.spectrometerModel = line.split(":")[1].trim();
        }
        if (line.includes("光谱仪波长范围:")) {
          this.wavelengthRange = line.split(":")[1].trim();
        }
        if (line.includes("创建时间:")) {
          this.samplingTime = line.split(":")[1].trim() + " 00:00:00";
        }
      });

      // 解析吸光度数据
      this.absorbanceData = [];
      let dataStarted = false;

      lines.forEach((line) => {
        // 检测数据部分开始
        if (line.includes("活动曲线")) {
          dataStarted = true;
          return;
        }

        // 处理数据行
        if (dataStarted && line.trim() && !line.includes(":")) {
          const parts = line.trim().split(/\s+/);
          if (parts.length >= 2) {
            const wavelength = parseFloat(parts[0]);
            const absorbance = parseFloat(parts[1]);
            if (!isNaN(wavelength) && !isNaN(absorbance)) {
              this.absorbanceData.push({
                wavelength,
                absorbance,
              });
            }
          }
        }
      });

      // 拼接吸光度字符串
      this.absorbanceString = this.absorbanceData
        .map((item) => item.absorbance.toString())
        .join(",");
    },
    async saveData() {
      // 这里可以添加保存数据的逻辑
      console.log("保存的数据:", {
        spectrometerModel: this.spectrometerModel,
        wavelengthRange: this.wavelengthRange,
        absorbanceData: this.absorbanceString,
      });
      this.form.samplingTime = this.samplingTime;
      this.form.instrumentNo = this.spectrometerModel;
      this.form.wavelength = this.absorbanceString;
      console.log("表单数据", this.form);
      try {
        await this.setInstrumentInfo();
      } catch (error) {
        this.$modal.msgError(error.message);
        return;
      }

      if (this.wavelengthRange) {
        const parts = this.wavelengthRange.split("--");
        if (parts.length === 2) {
          this.form.startWavelength = parseFloat(parts[0]);
          this.form.endWavelength = parseFloat(parts[1]);
        }
      }

      // 关闭弹窗
      this.showModal = false;
      this.resetForm();

      // 提示用户
      // 提示用户
      this.$message({
        message: "数据导入成功",
        type: "success",
      });
    },
    async setInstrumentInfo() {
      console.log("仪器编号", this.spectrometerModel);
      const response = await listInstrument({
        instrumentName: this.spectrometerModel,
      });
      if (response.code === 200 && response.rows?.length > 0) {
        this.form.instrumentId = response.rows[0].instrumentId;
        this.form.instrumentNo = response.rows[0].instrumentNo;
        this.form.instrumentName = response.rows[0].instrumentName;
        console.log("仪器信息", response.rows[0]);
      } else {
        throw new Error(
          "仪器【" + this.form.instrumentNo + "】不存在，请在仪器管理页面添加！"
        );
      }
    },
    resetForm() {
      this.fileContent = null;
      this.spectrometerModel = "";
      this.wavelengthRange = "";
      this.absorbanceData = [];
      this.absorbanceString = "";
      // this.$refs.fileInput.value = "";
    },

    /** 查询环境光谱列表 */
    getList() {
      this.loading = true;
      listEnv_spectrum(this.queryParams).then((response) => {
        this.env_spectrumList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        envSpectrumId: null,
        envSpectrumNo: null,
        wavelength: null,
        departmentName: null,
        departmentId: null,
        instrumentId: null,
        instrumentNo: null,
        instrumentName: null,
        startWavelength: null,
        endWavelength: null,
        samplingTime: null,
        builderId: null,
        builderName: null,
        remarks: null,
        isDelete: null,
        creatorId: null,
        creator: null,
        createTime: null,
        modifierId: null,
        modifier: null,
        modifyTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.envSpectrumId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;

      // 提取需要传给父组件的字段
      const selectedInfo = selection.map((item) => ({
        id: item.envSpectrumId,
        no: item.envSpectrumNo,
      }));

      // 把选中行的id和no传给父组件
      this.$emit("selection-change", selection);
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.form.builderId = this.$store.state.user.id;
      this.form.builderName = this.$store.state.user.name;
      this.title = "添加环境光谱";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const envSpectrumId = row.envSpectrumId || this.ids;
      getEnv_spectrum(envSpectrumId).then((response) => {
        this.form = response.data;
        console.log("修改数据", this.form);
        this.open = true;
        this.title = "修改环境光谱";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.envSpectrumId != null) {
            updateEnv_spectrum(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addEnv_spectrum(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const envSpectrumIds = row.envSpectrumId || this.ids;
      this.$modal
        .confirm('是否确认删除环境光谱编号为"' + envSpectrumIds + '"的数据项？')
        .then(function () {
          return delEnv_spectrum(envSpectrumIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "spectrum/env_spectrum/export",
        {
          ...this.queryParams,
        },
        `env_spectrum_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>

<style scoped>
.file-info {
  margin-top: 20px;
}

.upload-demo {
  text-align: center;
}

.el-upload__tip {
  margin-top: 10px;
}

.drawer-footer {
  /* width: 100%; */
  position: absolute;
  right: 10px;
  bottom: 10px;
}
</style>
